package com.qf.Dao.Impl;/*
 *
 */

import com.qf.Dao.GoodsDao;
import com.qf.Domain.Goods;
import com.qf.Utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GoodsDaoImpl implements GoodsDao {
    private QueryRunner qr=new QueryRunner();

    @Override
    public long selectCount(String where,  ArrayList<Object> list) {
        String sql="select count(*) from tb_goods"+where;
        Connection conn = DataSourceUtils.getConnection();
        try {
            return (long) qr.query(conn, sql, new ScalarHandler(), list.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            DataSourceUtils.closeAll(conn, null, null);
        }
    }

    @Override
    public List<Goods> selectData(int pageNum, int pageSize, String where,  ArrayList<Object> list) {
        String sql="select * from tb_goods"+where+" order by id limit ?,?";
        Connection conn = DataSourceUtils.getConnection();
        try {
            list.add((pageNum-1)*pageSize);
            list.add(pageSize);
            return qr.query(conn, sql, new BeanListHandler<>(Goods.class), list.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            DataSourceUtils.closeAll(conn, null, null);
        }
    }

    @Override
    public Goods selectById(int i) {
        String sql="select * from tb_goods where id=?";
        Connection conn = DataSourceUtils.getConnection();
        try {
            return qr.query(conn,sql,new BeanHandler<>(Goods.class),i);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
